package jsyf.oa.service.wechat.service_company;

import com.alibaba.fastjson.JSONObject;
import jsyf.oa.dao.wechat.service_otherCompany.CompanyMessageDao;
import jsyf.oa.dao.wechat.service_otherCompany.CompanyTokenDao;
import jsyf.oa.entity.wechat.service_company.TokenEntity;
import jsyf.oa.facade.wechat.config.WeChatConst;
import jsyf.oa.facade.wechat.service_company.CompanyTokenFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by jjx on 2018/4/7.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class CompanyTokenService implements CompanyTokenFacade {

    @Autowired
    private CompanyTokenDao companyTokenDao;

    @Autowired
    private CompanyMessageDao companyMessageDao;

    private  JSONObject jsonObject;

    private  String requestUrl = null;

    private  final  int wechat_application_push_type =2;

    //企业号通讯录类型(获取token使用)
    private  final int weChat_enterprise_contacts_type = 3;

    public JSONObject getJsonObject() {
        return jsonObject;
    }

    //通讯录获取(type=3)
    @Override
    public String getContactsToken(String jsonData) {
        //数据库获取公司信息
         jsonObject= companyMessageDao.getCompanyMessageByCompanyId(jsonData);
        //拼装url
        sendUrl(weChat_enterprise_contacts_type,jsonObject.getString("COMPANY_CORPID"),jsonObject.getString("CONTACTS_SECRET"));
        return getAccessToken(jsonData,weChat_enterprise_contacts_type);
    }

    //自建应用(type=2)
    @Override
    public String getApplicationToken(String jsonData,int type) {
        //数据库获取公司信息
         jsonObject= companyMessageDao.getCompanyMessageByCompanyId(jsonData);
        //拼装url
        sendUrl(weChat_enterprise_contacts_type,jsonObject.getString("COMPANY_CORPID"),jsonObject.getString("APPLICATION_ONE_SECRET"));
        return getAccessToken(jsonData,type);
    }

    //通过类型区分拼装url
    @Override
    public void sendUrl(int type,String corpID,String contactsSecret){
        switch (type) {
            //通讯录 -3
            case weChat_enterprise_contacts_type:
                requestUrl = WeChatConst.wechat_access_token_url.replace("ID", corpID).replace("SECRECT", contactsSecret);
                break;
            //推送应用 -2
            case wechat_application_push_type:
                requestUrl = WeChatConst.wechat_access_token_url.replace("ID", corpID).replace("SECRECT", contactsSecret);
                break;
        }
    }

    //发送请求获取---access_token
    public  JSONObject getServiceAccessToken(String jsonData, int type) {
        //发送请求或去新的-access_token
        JSONObject job = HttpUtil.request(requestUrl, "GET", null);
        if (null != job) {
            try {
                TokenEntity accessToken = new TokenEntity();
                accessToken.setAccessToken(job.getString("access_token"));
                accessToken.setExpiresIn(job.getInteger("expires_in"));
                accessToken.setType(type);
                accessToken.setCompanyId(jsonData);
                companyTokenDao.saveAccessToken(accessToken, type);
            } catch (Exception e) {
                return null;
            }
        }
        return job;
    }

    //获取本地数据库中的access_token记录
    public  String getAccessToken(String jsonData,int type) {
        List<JSONObject> jobs = companyTokenDao.getAccessTokenByType(jsonData,type);
        if (null != jobs && jobs.size() > 0) {
            //判断是否超2小时（提前200秒存储）
            TokenEntity entity = (TokenEntity) companyTokenDao.convertJson2Entity(jobs.get(0));
            if (Math.floor((companyTokenDao.getCurrentTime().getTime() - entity.getCreateTime().getTime()) / 1000) > entity.getExpiresIn() - 200) {
                return this.getServiceAccessToken(jsonData,type).getString("access_token");
            } else {
                return jobs.get(0).getString("accessToken");
            }
        } else {
            //token不存在
            return this.getServiceAccessToken(jsonData,type).getString("access_token");
        }
    }

}
